﻿using Common;
using Log4_Net;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Http.HeartBeat
{
    public class HeartBeatService : BackgroundService
    {
        IHttpClientHelper _IHttpClientHelper;
        ILogger _logger;
        public HeartBeatService(IHttpClientHelper IHttpClientHelper, ILogHelper logger)
        {
            _IHttpClientHelper = IHttpClientHelper;
            _logger = logger.GetLogger<HeartBeatService>();
        }
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    IConfiguration configuration = Singleton<IConfiguration>.Instance;

                    var input = new HeartBeatInput()
                    {
                        Description = configuration["HeartBeat:Description"],
                        NodeName = configuration["HeartBeat:NodeName"],
                        UserId = configuration["HeartBeat:UserId"],
                         Received = configuration["HeartBeat:Received"],
                    };
                    var result = await _IHttpClientHelper.PostAsync(_IHttpClientHelper.GetHost() + "/Nodes/HeartBeat", input.ToJson());
                    //_logger.LogDebug(result);
                    await Task.Delay(TimeSpan.FromMinutes(configuration["HeartBeat:Delay"].ToInt()), CancellationToken.None);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex.Message + ex.StackTrace);
                }
            }
        }
        public override void Dispose()
        {
            base.Dispose();
        }
    }
}
